<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.name" placeholder="商品名称" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.status" placeholder="商品状态" clearable style="width: 130px" class="filter-item">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                新增商品
            </el-button>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column label="商品ID" prop="id" align="center" width="80" />
            <el-table-column label="商品图片" align="center" width="120">
                <template slot-scope="scope">
                    <el-image v-for="(image, index) in scope.row.images" :key="index"
                        style="width: 50px; height: 50px; margin-right: 5px" :src="image"
                        :preview-src-list="scope.row.images" />
                </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" align="center" />
            <el-table-column label="价格" prop="price" align="center" width="100">
                <template slot-scope="scope">
                    ¥{{ scope.row.price }}
                </template>
            </el-table-column>
            <el-table-column label="库存" prop="stock" align="center" width="100" />
            <el-table-column label="状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                        {{ scope.row.status === 1 ? '上架' : '下架' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
            <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">
                        编辑
                    </el-button>
                    <el-button :type="scope.row.status === 1 ? 'warning' : 'success'" size="mini"
                        @click="handleStatusChange(scope.row)">
                        {{ scope.row.status === 1 ? '下架' : '上架' }}
                    </el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <!-- 新增/编辑商品对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="temp.name" />
                </el-form-item>
                <el-form-item label="商品图片" prop="images">
                    <el-upload class="upload-demo" :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove"
                        :on-success="handleImageSuccess" :before-upload="beforeImageUpload" :file-list="fileList"
                        list-type="picture-card" multiple>
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="temp.price" :precision="2" :step="0.1" :min="0" />
                </el-form-item>
                <el-form-item label="商品库存" prop="stock">
                    <el-input-number v-model="temp.stock" :min="0" :step="1" />
                </el-form-item>
                <el-form-item label="商品介绍" prop="description">
                    <el-input v-model="temp.description" type="textarea" :rows="4" placeholder="请输入商品介绍" />
                </el-form-item>
                <el-form-item label="商品状态" prop="status">
                    <el-radio-group v-model="temp.status">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getProductList, createProduct, updateProduct, deleteProduct, uploadImage } from '@/api/shop'
import Pagination from '@/components/Pagination'

export default {
    name: 'Product',
    components: { Pagination },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: false,
            listQuery: {
                page: 1,
                limit: 10,
                name: undefined,
                status: undefined
            },
            statusOptions: [
                { label: '上架', value: 1 },
                { label: '下架', value: 0 }
            ],
            dialogVisible: false,
            dialogTitle: '',
            temp: {
                id: undefined,
                name: '',
                images: [],
                price: 0,
                stock: 0,
                description: '',
                status: 1
            },
            fileList: [],
            rules: {
                name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                images: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
                price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
                status: [{ required: true, message: '请选择商品状态', trigger: 'change' }]
            },
            uploadUrl: process.env.VUE_APP_BASE_API + '/upload/image'
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            this.listLoading = true
            try {
                const { data } = await getProductList(this.listQuery)
                this.list = data.items
                this.total = data.total
            } catch (error) {
                console.error('获取商品列表失败:', error)
            }
            this.listLoading = false
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleCreate() {
            this.dialogTitle = '新增商品'
            this.dialogVisible = true
            this.temp = {
                id: undefined,
                name: '',
                images: [],
                price: 0,
                stock: 0,
                description: '',
                status: 1
            }
            this.fileList = []
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        handleUpdate(row) {
            this.dialogTitle = '编辑商品'
            this.dialogVisible = true
            this.temp = Object.assign({}, row)
            this.fileList = row.images.map(url => ({
                name: url.split('/').pop(),
                url: url
            }))
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        handleRemove(file, fileList) {
            this.temp.images = fileList.map(file => file.url || file.response.data.url)
        },
        handlePreview(file) {
            // 预览图片
        },
        async handleImageSuccess(res, file) {
            if (res.code === 20000) {
                this.temp.images.push(res.data.url)
                this.$message.success('上传成功')
            } else {
                this.$message.error('上传失败')
            }
        },
        beforeImageUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG/PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        async handleStatusChange(row) {
            try {
                const newStatus = row.status === 1 ? 0 : 1
                await updateProduct({
                    ...row,
                    status: newStatus
                })
                this.$message.success(newStatus === 1 ? '上架成功' : '下架成功')
                this.getList()
            } catch (error) {
                console.error('更新商品状态失败:', error)
                this.$message.error('操作失败')
            }
        },
        async handleDelete(row) {
            try {
                await this.$confirm('确认删除该商品吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                await deleteProduct(row.id)
                this.$message.success('删除成功')
                this.getList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除商品失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },
        async submitForm() {
            this.$refs['dataForm'].validate(async (valid) => {
                if (valid) {
                    try {
                        if (this.temp.id) {
                            await updateProduct(this.temp)
                        } else {
                            await createProduct(this.temp)
                        }
                        this.$message.success(this.temp.id ? '修改成功' : '新增成功')
                        this.dialogVisible = false
                        this.getList()
                    } catch (error) {
                        console.error(this.temp.id ? '修改商品失败:' : '新增商品失败:', error)
                        this.$message.error(this.temp.id ? '修改失败' : '新增失败')
                    }
                }
            })
        }
    }
}
</script>

<style scoped>
.filter-container {
    padding-bottom: 10px;
}

.upload-demo {
    width: 100%;
}
</style> 